#!/usr/bin/python3
# -*- coding: utf-8 -*-
# -*- 作者： codervibe -*-
# -*- 时间: 18 ：46 -*-
# -*- 获取某个城市的天气 -*-
# -*-  1.9  -*-

import argparse
import json
import urllib
import urllib.error as error
import urllib.request as request

# 设定帮助文档标题
parser = argparse.ArgumentParser(description='your script description')
# 设定一个参数 c 或者 city 将这个参数传入并查询
parser.add_argument('-c', '--city', type=str, help='Inquired city', metavar="city_name")
# 设定一个参数 c 或者 city 将这个参数传入并查询
parser.add_argument('-v', help='Optional parameters', action='version', version="Weater version 1.2.0")

args = parser.parse_args()

# 如果没有传入参数则直接输出帮助信息并退出
if not args.city:
    parser.print_help()
    exit()

city = args.city
# ---------------------------------------------------------------------------------------------------


# ---------------------------------------------------------------------------------------------------
print("正在查询" + args.city + "的天气")


# 天气预报 查询示例

def WeatherForecastQueryExample():
    api_url = 'https://apis.juhe.cn/simpleWeather/query'
    # 空气质量等级
    aqi_level = ""
    # 空气质量对健康的影响
    airQualityOnHealth = ""
    # 建议采取的措施
    recommendedAction = ""
    aqi_i = 0
    params_dict = {
        "city": city,  # 查询天气的城市名称，如：北京、苏州、上海
        "key": "6293d8addffef3a87e9250b6bf96b0a9",  # 您申请的接口API接口请求Key
    }
    params = urllib.parse.urlencode(params_dict)
    try:
        req = request.Request(api_url, params.encode())
        response = request.urlopen(req)
        content = response.read()
        if content:
            try:
                result = json.loads(content)
                error_code = result['error_code']
                if error_code == 0:
                    temperature = result['result']['realtime']['temperature']
                    humidity = result['result']['realtime']['humidity']
                    info = result['result']['realtime']['info']
                    wid = result['result']['realtime']['wid']
                    direct = result['result']['realtime']['direct']
                    power = result['result']['realtime']['power']
                    aqi = result['result']['realtime']['aqi']
                    aqi_i = int(aqi)
                    if 0 <= aqi_i <= 50:
                        aqi_level = "优"
                        airQualityOnHealth = "空气质量令人满意，基本无空气污染。"
                        recommendedAction = "各类人群可正常活动"
                    if 51 <= aqi_i <= 100:
                        aqi_level = "良"
                        airQualityOnHealth = "空气质量可接受，某些污染物对极少数敏感人群健康有较弱影响。"
                        recommendedAction = "极少数敏感人群应减少户外活动。"
                    if 101 <= aqi_i <= 150:
                        aqi_level = "轻度污染"
                        airQualityOnHealth = "易感人群有症状有轻度加剧，健康人群出现刺激症状。"
                        recommendedAction = "老人、儿童、呼吸系统等疾病患者减少长时间、高强度的户外活动"
                    if 151 <= aqi_i <= 200:
                        aqi_level = "中度污染"
                        airQualityOnHealth = "进一步加剧易感人群症状，会对健康人群的呼吸系统有影响。"
                        recommendedAction = "儿童、老人、呼吸系统等疾病患者及一般人群减少户外活动"
                    if 201 <= aqi_i <= 300:
                        aqi_level = "重度污染"
                        airQualityOnHealth = "心脏病和肺病患者症状加剧运动耐受力降低，健康人群出现症状"
                        recommendedAction = "儿童、老人、呼吸系统等疾病患者及一般人群停止或减少户外运动"
                    if aqi_i >= 300:
                        aqi_level = "严重污染"
                        airQualityOnHealth = "健康人群运动耐受力降低，有明显强烈症状，可能导致疾病"
                        recommendedAction = "儿童、老人、呼吸系统等疾病患者及一般人群停止户外活动"
                    print(
                        "温度：%s\n湿度：%s\n天气：%s\n天气标识：%s\n风向：%s\n风力：%s\n空气质量：%s\n空气质量等级：%s\n对健康的影响: %s\n建议采取的措施: %s\n" % (
                            temperature, humidity, info, wid, direct, power, aqi, aqi_level, airQualityOnHealth,
                            recommendedAction))
                else:
                    print("请求失败:%s %s" % (result['error_code'], result['reason']))
            except Exception as e:
                print("解析结果异常：%s" % e)
        else:
            # 可能网络异常等问题，无法获取返回内容，请求异常
            print("请求异常")
    except error.HTTPError as err:
        print(err)
    except error.URLError as err:
        # 其他异常
        print(err)


# 天气预报查询示例
def main():
    WeatherForecastQueryExample()


if __name__ == '__main__':
    main()
